//
//  OncewayObstacle.m
//  StarBugs
//
//  Created by ?? ? on 3/28/12.
//  Copyright 2012 antisword@playorca.com. All rights reserved.
//

#include "Object/OncewayObstacle.h"
#include "Util/ImageManager.h"
#include "Util/SoundManager.h"
#include "Util/Util.h"

using namespace cocos2d;


OncewayObstacle::OncewayObstacle()
{

    mainSprite = ImageManager::getSpriteWithXml2(kImagesheet_GameSource, "onceway_on");
    addChild(mainSprite);
    objectType = objectType_onceway;
    
    CCSpriteFrame *frame;
    char txt[16];
    for(int i = 0; i < 5; i ++)
    {
        sprintf(txt, "onceway_off_%d", i + 1);
        frame = ImageManager::getFrameWithXml2(kImagesheet_GameSource, txt);
        frameArray->addObject(frame);
    }
    closeFlg = false;
}

void OncewayObstacle::setBody(b2World *world)
{
    mainSprite->setPosition(position);
    mainSprite->setRotation(-bodyAngle);
}


void OncewayObstacle::setBodyAngle(bool isInv)
{
    if(isInv)
        bodyAngle += 10;
    else
        bodyAngle -= 10;
    
    mainSprite->setRotation(-bodyAngle);
}

bool OncewayObstacle::checkThrow(cocos2d::CCPoint pt)
{
    CCLog("pt : %f, %f, center : %f,  %f", pt.x, pt.y, mainSprite->getPosition().x, mainSprite->getPosition().y);
    CCPoint rotatedPt;
    rotatedPt = ccpRotateByAngle(pt, mainSprite->getPosition(), CC_DEGREES_TO_RADIANS(bodyAngle));
    if(Util::makeRectWithSprite(mainSprite).containsPoint(rotatedPt))
        return true;
    
    return false;
}

void OncewayObstacle::startCloseDoor(b2World *_world)
{
    if(closeFlg == true)
        return;
    SoundManager::PlaySoundEffect(sndEffect_onceWay);
    worldTmp = _world;
    schedule(schedule_selector(OncewayObstacle::closeTick), 0.1);
    closeCnt = 0;
    closeFlg = true;
}

void OncewayObstacle::closeTick(float dt)
{
    closeCnt ++;
    mainSprite->setDisplayFrame((CCSpriteFrame *)frameArray->objectAtIndex(closeCnt - 1));
    if(closeCnt == 4)
        call_close();
    if(closeCnt == 5)
        unschedule(schedule_selector(OncewayObstacle::closeTick));
}

void OncewayObstacle::call_close()
{
    b2BodyDef bodyDef;
	bodyDef.type = b2_staticBody;
	bodyDef.position.Set(position.x/PTM_RATIO, position.y/PTM_RATIO);
	bodyDef.userData = mainSprite;
	mainBody = worldTmp->CreateBody(&bodyDef);
	
    b2PolygonShape rec;
    rec.SetAsBox(6 / PTM_RATIO, 37 / PTM_RATIO);
	
	b2FixtureDef fixtureDef;
	fixtureDef.shape = &rec;	
    fixtureDef.restitution = 0.5f;
	mainBody->CreateFixture(&fixtureDef);
    mainBody->SetTransform(mainBody->GetPosition(), CC_DEGREES_TO_RADIANS(bodyAngle));
}

void OncewayObstacle::removeBody(b2World *_world)
{
    if(mainBody != NULL)
        _world->DestroyBody(mainBody);
}

void OncewayObstacle::resetObstacle()
{
    removeBody(worldTmp);
    mainBody = NULL;
    closeFlg = false;
    mainSprite->setDisplayFrame(ImageManager::getFrameWithXml2(kImagesheet_GameSource, "onceway_on"));
}